//门市打印编辑
import { message, Form, Drawer, Alert, Input, InputNumber, Button } from "antd";
import { useEffect, useRef, useState } from "react";
import LeftContent from "./LeftContent";
import RightContent from "./RightContent";
import Typography from "@/pages/OrderModule/common/components/Typography";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import CommonLoading from "@/components/CommonLoading";
import { queryFieldManageList, addKuaimaiOp, updateKuaimaiOp, copyKuaimaiOp, getTableDataOp } from "../../../service";
import styles from "./index.module.less";
import { isJSON } from "@/utils/utils.jsx";
import { getCurrentUser } from "@/utils/authority";
import CommonDrawer from '@/components/CommonDrawer';
import { find } from "lodash";

//类型
const textMap = {
	1: "新增",
	2: "编辑",
	3: "复制"
};

const sizeScale = 0.47; //缩放比例

const EditStoreTemplate = ({ editStoreItem, recordData, type, handleCancel, handleOk }) => {
	const { visible } = editStoreItem;

	const [currId, setCurrId] = useState(undefined); //当前操作对应数据框id
	const [updateKey, setUpdateKey] = useState(0);
	const [viewContent, setViewContent] = useState([]); //模版内容数据
	const [item, setItem] = useState({}); //1.预览弹窗,2:插入表格
	const [printArr, setPrintArr] = useState({}); //右侧勾选字段展示
	const [weight, setWeight] = useState(recordData.sizeWidth); //当前宽度
	const [height, setHeight] = useState(recordData.sizeHeight); //当前高度
	const [loading, setLoading] = useState(false);

	const [form] = Form.useForm();

	useEffect(() => {
		getFieldManageList();
	}, []);

	//获取商品和订单打印项
	useEffect(() => {
		if (type == 2 || type == 3) {
			//编辑  复制
			setViewContent(polymerData(isJSON(recordData.viewContent) ? JSON.parse(recordData.viewContent) : {}));
			setTimeout(() => form.resetFields(), 200); //简单制造异步重置表单
		}
	}, [type, recordData]);

	const currentUuid = getCurrentUser()?.uuid
	//聚合数据源
	const polymerData = data => {
		const arr = [];
		Object.keys(data).map(item => {
			if (data[item] instanceof Object) {
				data[item].length &&
					data[item].map(child => {
						if (item == "table") {
							const arrHearder = child.value ? child.value.split("#") : ["", ""];
							arr.push({
								...child,
								type: item,
								left: (sizeScale * 100 * 400 * (child.left - 15)) / 40000,
								top: (sizeScale * 100 * 640 * child.top) / 64000,
								width: (sizeScale * 100 * 400 * child.width) / 40000,
								height: (sizeScale * 100 * 640 * child.height) / 64000,
								leftHeader: arrHearder[0],
								rightHeader: arrHearder[1]
							});
						} else {
							const getFontSize = () => {
								const bigValueMap = {
									'722324': ['分拣框'],
									'727786': ['订单单多件'],
								}
								const littleBigValueMap = {
									'722324': ['用户简称', '款式编码', '商品编码', '货品总数', '订单单多件'],
									'726536': ['分拣框', '用户简称', '款式编码', '货品总数', '订单单多件'],
									'727786': ['用户简称', '分拣框', '商品编码', '货品总数'],
									'721261': ['用户简称', '商品编码', '订单单多件', '货品总数', '分拣框'],
								}
								return bigValueMap[currentUuid]?.includes(child.value) ? 3 : littleBigValueMap[currentUuid]?.includes(child.value) ? 2 : 1;
							}
							arr.push({
								...child,
								type: item,
								left: (sizeScale * 100 * 400 * (child.left - 15)) / 40000,
								top: (sizeScale * 100 * 640 * child.top) / 64000,
								width: (sizeScale * 100 * 400 * child.width) / 40000,
								height: (sizeScale * 100 * 640 * child.height) / 64000,
								value: child.value,
								widthMultiple: getFontSize(),
								heightMultiple: getFontSize(),
								// || printMap[child.fieldName]
							});
						}
					});
				if (item == "uniqueCode" && Object.keys(data[item]).length) {
					arr.push({
						...data[item],
						type: item,
						left: (sizeScale * 100 * 400 * (data[item].left - 15)) / 40000,
						top: (sizeScale * 100 * 640 * data[item].top) / 64000,
						width: (sizeScale * 100 * 400 * data[item].width) / 40000,
						height: (sizeScale * 100 * 640 * data[item].height) / 64000,
						value: "525000000000000001"
					});
				}
			}
		});
		// console.log(1, data, arr)
		return arr;
	};

	//获取右侧展示字段
	const getFieldManageList = async () => {
		setLoading(true);
		const { data = {}, success } = await queryFieldManageList();
		if (success) {
			setPrintArr(data);
		}
		setLoading(false);
	};

	//format提交模板数据
	const formatTemplateData = arr => {
		//需要的数据格式
		const obj = {
			customTexts: [],
			customQrCodes: [],
			customBarCodes: [],
			orderInfo: [],
			goodsInfo: [],
			otherInfo: [],
			// uniqueCode: {},
			table: []
		};
		//formart相关字段
		arr.map(item => {
			const width = (item.width * 100) / (sizeScale * 100),
				height = (item.height * 100) / (sizeScale * 100),
				left = (item.left * 100) / (sizeScale * 100) + 15,
				top = (item.top * 100) / (sizeScale * 100);
			if (item.type == "uniqueCode" && Object.keys(item).length) {
				obj.uniqueCode = { ...item, width, height, left, top };
			} else if (item.type == "customQrCodes") {
				//如果是二维码  传区间值
				let cellWidth = Math.ceil(width / (3.6 * 8)); //0-288 分十个梯度
				cellWidth = Math.max(cellWidth, 4);
				cellWidth = Math.min(cellWidth, 10);
				obj.customQrCodes.push({ ...item, width, height, left, top, cellWidth });
			} else if (item.type == "table") {
				obj[item.type].push({ ...item, width, height, left, top, value: `${item.leftHeader}#${item.rightHeader}` });
			} else {
				obj[item.type].push({ ...item, width, height, left, top });
			}
		});
		// console.log(2, obj)
		return obj;
	};

	//点击保存
	const handleSave = () => {
		//默认模板编辑 isdefault 字段
		form.validateFields().then(val => {
			saveTemplate({
				...recordData,
				...val,
				viewContent: JSON.stringify(formatTemplateData(viewContent))
			});
		});
	};

	//提交保存
	const saveTemplate = async val => {
		setLoading(true);
		let res;
		if (type == 2) {
			//编辑走更新接口
			res = await updateKuaimaiOp(val);
		} else {
			//新增｜复制
			if (type == 1) {
				//新增
				res = await addKuaimaiOp(val);
			} else {
				//复制
				val.ecStoreList = [];
				val.ecStoreIds = '';
				res = await copyKuaimaiOp(val);
			}
		}
		const { success } = res;
		if (success) {
			message.success("操作成功");
			handleOk();
		}
		setLoading(false);
	};

	// 重置为默认模板
	const handleReset = async () => {
		START_LOADING();
		const { success, data } = await getTableDataOp({ labelType: 4 });
		if (success) {
			const { viewContent, sizeWidth, sizeHeight, templateName  } = find(data, ['templateAttribute', 1]) || {};
			setViewContent(polymerData(isJSON(viewContent) ? JSON.parse(viewContent) : {}));
			setWeight(sizeWidth);
			setHeight(sizeHeight);
			form.setFieldsValue({ 
				templateName: templateName,
				sizeWidth: sizeWidth,
				sizeHeight: sizeHeight,
			});
		}
		END_LOADING();
	}

	//底部按钮渲染
	const footerRender = () => {
		return (
			<div className={styles.footer}>
				<Button style={{ marginRight: "16px" }} onClick={() => handleCancel()}>
					取消
				</Button>
				<Button style={{ marginRight: "16px" }} onClick={handleReset}>
					重置
				</Button>
				<Button
					onClick={() => {
						handleSave();
					}}
					type="primary"
				>
					确认
				</Button>
			</div>
		);
	};

	//左侧展示区
	const LeftContentProps = {
		currId,
		printArr,
		sizeScale,
		weight,
		height,
		viewContent,
		updateData(val) {
			setViewContent(val);
		},
		updateId(val) {
			setCurrId(val);
		},
		handleClickEdit(obj) {
			setItem({ ...obj, visible: 2 });
		}
	};

	//右侧展示区
	const RightContentProps = {
		currId,
		printArr,
		// printMap,
		viewContent,
		updateData(val) {
			setViewContent(val);
		},
		updateId(val) {
			setCurrId(val);
		},
		handleClickInsert() {
			setItem({ visible: 2 });
		}
	};

	return (
		<CommonDrawer
			title={`${textMap[type]}门市打印模板`}
			open={visible}
			onClose={handleCancel}
			onOk={() => {
				handleSave();
			}}
			footer={footerRender()}
			width="80%"
			// okText="保存"
		>
			<>
				<div>
					<Alert
						showIcon
						style={{ marginBottom: "24px" }}
						message={<Typography as="s1">模板的打印效果以实际打印机打印效果为准，预览仅作为参考</Typography>}
					/>
					<SubTitle title={"模板信息"} as="s2" symbol />
					<Form
						name="edit-store-template"
						form={form}
						layout="inline"
						initialValues={{ ...recordData }}
						style={{ margin: "24px 0px" }}
					>
						<Form.Item
							name="templateName"
							label="模版名称"
							rules={[
								{ required: true, message: "请输入模版名称" },
								{ max: 50, message: "最多输入50个字符！" }
							]}
							shouldUpdate
						>
							<Input placeholder="请输入模版名称" style={{ width: "180px", marginRight: "12px" }} />
						</Form.Item>
						<Form.Item label="模板宽高(毫米)" className={styles.labelReqire}>
							<div style={{ display: "flex" }}>
								<Form.Item name="sizeWidth" rules={[{ required: true, message: "请输入模版宽度" }]}>
									<InputNumber
										min={1}
										onChange={e => {
											setWeight(e);
										}}
									/>
								</Form.Item>
								<span>X</span>
								<Form.Item name="sizeHeight" rules={[{ required: true, message: "请输入模版高度" }]}>
									<InputNumber
										min={1}
										onChange={e => {
											setHeight(e);
										}}
									/>
								</Form.Item>
							</div>
						</Form.Item>
					</Form>
					<div>
						<div style={{ display: "flex", justifyContent: "space-between" }}>
							<LeftContent {...LeftContentProps} />
							<RightContent {...RightContentProps} />
						</div>
					</div>
				</div>
			</>
			<CommonLoading loading={loading} />
		</CommonDrawer>
	);
};

export default EditStoreTemplate;
